<template>
  <div class="player">
    <!-- 全屏播放器 -->
    <NormalPlayer :totalTime="totalTime" :currentTime="currentTime"></NormalPlayer>
    <MiniPlayer></MiniPlayer>
    <ListPlayer ref="listPlayer"></ListPlayer>
    <!--播放 -->
    <audio :src="currentSongs.url" ref="audio" @timeupdate="timeupdate" @ended="ended"></audio>
  </div>
</template>

<script>
import NormalPlayer from '@/components/player/NormalPlayer'
import MiniPlayer from '@/components/player/MiniPlayer'
import ListPlayer from '@/components/player/ListPlayer'
import mode from '../store/modeType'
import { mapGetters, mapActions } from 'vuex'
import { getRandomIntInclusive } from '@/tools/tools'
export default {
  data () {
    return {
      totalTime: 0, // 总时间
      currentTime: 0 // 当前播放歌曲时间
    }
  },
  methods: {
    ...mapActions(['setCurrentIndex']),
    timeupdate (e) {
      this.currentTime = e.target.currentTime
    },
    // 结束之后监听播放模式
    ended () {
      // 循环播放 当前播放歌曲下标+1
      if (this.modeType === mode.loop) {
        // 使用setCurrentIndex方法设置
        this.setCurrentIndex(this.currentIndex + 1)
      } else if (this.modeType === mode.one) {
        // 单曲播放 重新播放当前歌曲
        this.$refs.audio.play()
      } else {
        // 随机播放
        const index = getRandomIntInclusive(0, this.getSongs.length - 1)
        this.setCurrentIndex(index)
      }
    }
  },
  components: {
    NormalPlayer,
    MiniPlayer,
    ListPlayer
  },
  computed: {
    ...mapGetters(['currentSongs', 'isPlaying', 'currentIndex', 'curTime', 'modeType', 'getSongs'])
  },
  watch: {
    isPlaying (newVal, oldVal) {
      if (newVal) {
        this.$refs.audio.play()
      } else {
        this.$refs.audio.pause()
      }
    },
    currentIndex () {
      this.$refs.audio.oncanplay = () => {
        // 重新获取歌曲时长
        this.totalTime = this.$refs.audio.duration
        if (this.isPlaying) {
          this.$refs.audio.play()
        } else {
          this.$refs.audio.pause()
        }
      }
    },
    curTime (newVal, oldVal) {
      this.$refs.audio.currentTime = newVal
    }
  },
  mounted () {
    this.$refs.audio.oncanplay = () => {
      // duration当前播放歌曲的总时长
      // oncanplay 歌曲是否可播放
      this.totalTime = this.$refs.audio.duration
    }
  }
}
</script>

<style lang="scss" scoped>
.player {
}
</style>
